package com.kyubi.common.grammar;

import java.util.Vector;

/**
 * This class represents the Tree node for the syntax grammar
 * The rule S -> VP NP is represented as
 * 			|	(head) S |
 * 			/	/	\	\...
 * 		| VP |	| NP |	| children |
 * @see com.kyubi.common.grammar.Tree
 * @author anand
 *
 */
public class TreeNode {

	private String head;
	private TreeNode parent;
	private Vector<TreeNode> children;
	private StringBuffer text;
	
	/**
	 * Constructor
	 * @param current	the head of the node (the head of the rule)
	 */
	public TreeNode(String current) {
		this.head = current;
		this.text = new StringBuffer();
		children = new Vector<TreeNode>();
	}
	
	/**
	 * Function to set the head of the node (rule)
	 * @param value	the value of the head
	 */
	private void setHead(String value) {
		this.head = value;
	}
	
	/**
	 * Function to get the head of the tree node 
	 * @return	the head value
	 */
	public String getHead() {
		return head;
	}
	
	/**
	 * Function to get the parent node
	 * @return	the parent node
	 */
	public TreeNode getParent() {
		return parent;
	}
	
	/**
	 * Function to set the parent node for this TreeNode
	 * @param parent	the parent TreeNode
	 */
	public void setParent(TreeNode parent) {
		this.parent = parent;
	}
	
	/**
	 * 	Function to the children TreeNodes
	 * @return	the Vector of child TreeNodes
	 */
	public Vector<TreeNode> getChildren() {
		return children;
	}
	
	/**
	 * Function to add the TreeNode as the child of this node
	 * @param tNode	the child TreeNode
	 */
	public void addChild(TreeNode tNode) {
		children.add(tNode);
	}
	
	/**
	 * Function to check if a given TreeNode is equal to this node
	 * @param b	the TreeNode to check against
	 * @return	true	if equal
	 * @return	false	otherwise
	 */
	public boolean equals(TreeNode b) {
		if(this.head == b.getHead()) {
			return true;
		} else {
			return false;
		}
	}
	
	/**
	 * Function to get the text of the current node
	 * @return	the text
	 */
	public String getText() {
		return this.text.toString();
	}
	
	/**
	 * Function to set the text for this node
	 * @param text	the text value
	 */
	public void setText(String text) {
		this.text = new StringBuffer(text);
	}
	
	/**
	 * Function to append the child TreeNode texts to the text of this node
	 */
	public void populateText() {
		this.text = new StringBuffer();
		for(int i=children.size()-1; i>=0; i--) {
			this.text.append(children.get(i).getText());
			
			if(i != 0) {
				this.text.append(" ");
			}
		}
	}
}
